from constants import *
import pygame,random,time
from task import Task
from ds import DS

#####################################################
#                                                   #
#  List class:                                      # 
#                                                   #
#  The List class implements a list that can        #
#  be visualized through the display function.      #
#                                                   #
#  Tasks can be added to any position within the    #
#  list, as long as that spot is not yet occupied   #
#                                                   # 
#  Author: Felix Rohrer                             #     
#  Course: CS MET 575                               #
#  Year:   2011                                     #
#                                                   #
#####################################################

class List(DS):

  def __init__(self, numOfElem, pos, name='',drawAreaDim=(700,600)):
    DS.__init__(self,numOfElem, pos, name, drawAreaDim)
    self.DSType = 'LIST'

  def display(self, canvas):
    # draw rects that belong currently to the queue
    DS.display(self,canvas,bgColor=LIST_BG_COLOR)

    # draw name into task
    canvas.blit(self.textFont.render(self.name, True, (0,0,255)),(self.pos[0]+2, self.pos[1]+self.size[1]+2))

  # insert task to specific position in list
  def insert(self,task,pos):
      if self.tasks[pos] is None or self.tasks[pos] == task:
        if task.currentDS == self.name:
          self.remove(task)

        # add this task to the list
        task.setDS(self)
        self.tasks[pos] = task
        task.setPos((self.pos[0]+10+50*pos,self.pos[1]+10))
      else:
        # try to find another free spot in this list
        for i in range(len(self.tasks)):
          if self.tasks[i] is None:
            self.insert(task,i)
            return
        print 'position occupied, cannot insert. '

  # remove a certain task from this list 
  def remove(self,task):
    try:
      ind = self.tasks.index(task)
      task.setDS(None)
      self.tasks[ind] = None
    except ValueError:
      print 'current task not in this list. '

  # returns next task in list or False if list empty
  def nextTask(self):
    for i in self.tasks:
      if i is not None:
        return i
    return False
   
  # returns a random task from the list
  def randomTask(self,onlyReadyTasks=False):
    t = []
    for i in self.tasks:
      if i is not None:
        if onlyReadyTasks:
          if i.curExecTime == i.execTime:
            t.append(i)
        else:
          t.append(i)
    if t == []:
      return False
    choice = random.choice(t)
    del t[:]
    return choice
   
  # returns true if entire list empty
  def isEmpty(self):
    for i in self.tasks:
      if i is not None:
        return False
    return True
